#include <cctype>
#include <cstddef>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <strstream>
#include <vector>
#include <string>

using namespace std;

bool my_is_aplha(string pstr){
    for(size_t i=0;i<pstr.size();i++){
        if(isalpha(pstr[i]==0)){
            return 0;
        }
    }
    return 1;
}

class Word{
public:
    Word(string wd):word(wd){}

    string word;
    int freq=1;
};

class Bible{
public:
    Bible(){    vec.reserve(5000);  }

    void put(string key){
        for(size_t i=0;i<vec.size();i++){
            if(key==vec[i].word){
                vec[i].freq++;
                return;
            }
        }
        Word word(key);
        vec.emplace_back(word);
    }

    void read(string &filename){
        string line;
        string word;
        int freq;
        ifstream ifs(filename);
        while(getline(ifs,line)){
            ifs>>word>>freq;
            cout<<word<<"  "<<freq<<endl;
        }

    }

    void store(string & filename){
        ofstream ofs(filename);
        if(!ofs.good()){
            cout<<"--- ofs Open Fail ---"<<endl;
        }
        
        for(auto it=vec.begin();it<vec.end();it++){
            ofs<<(*it).word<<" "<<(*it).freq<<endl;
        }
        
        cout<<"--- Store Finish ---"<<endl;
    }


private:
    vector<Word> vec;
};


void test(){
    ifstream ifs("./The_Holy_Bible.txt");
    if(!ifs.good()){
        cout<<"--- Bible open Fail ---";
        return;
    }
    Bible *bib=new Bible();

    string word;
    while(ifs>>word){
        if(my_is_aplha(word)){
            bib->put(word);
        }
    }

    string filename="./WordCounter.txt";
    bib->store(filename);

    sleep(2);

    string readfile="./WordCounter.txt";
    bib->read(readfile);
}

int main()
{
 test();
 return 0;
}

